import cv2
import datetime
import os
import threading
import time
from qiniu import Auth, put_file


class recordVideoClass():
    def __init__(self):
        self.isRecord = True  # 是否录制
        self.isRecording = False  # 是否正在录制
        self.isUpdate = True  # 是否上传到七牛
        self.isDelete = True  # 是否上传到七牛后删除
        self.startTime = 0  # 录制开始时间 零点
        self.endTime = 86400  # 录制结束时间 24点
        self.path = 'mp4'  # 保存目录
        self.recordTime = 10  # 录制时长
        self.videoFps = 15  # 录制视频fps
        self.ipCameraUrl = 'http://admin:admin@192.168.0.101:8081'  # ip摄像头地址
        self.access_key = 'access_keyfaewaefw'
        self.secret_key = 'secret_keyefhjtswef'
        self.bucket_name = 'qr-heanny-cn' #上传的空间名
        self.nowSecond = self.getNowSecond()

    def run(self):
        while self.isRecord:
            if self.nowSecond >= self.startTime and self.nowSecond <= self.endTime and not self.isRecording:
                self.recordVideo()
            else:
                time.sleep(1)

    def getNowSecond(self):
        h = datetime.datetime.now().hour
        m = datetime.datetime.now().minute
        s = datetime.datetime.now().second
        return h * 60 * 60 + m * 60 + s

    def recordVideo(self):
        self.isRecording = True
        print('开始录制视频……')
        camera = cv2.VideoCapture(self.ipCameraUrl)  # 获取摄像头
        fps = camera.get(cv2.CAP_PROP_FPS)  # 获取帧率
        width = int(camera.get(cv2.CAP_PROP_FRAME_WIDTH))  # 一定要转int 否则是浮点数
        height = int(camera.get(cv2.CAP_PROP_FRAME_HEIGHT))
        size = (width, height)  # 大小
        fileName = '{}.mp4'.format(time.strftime("%Y-%m-%d %H_%M_%S", time.localtime()))
        filePath = '{}/{}'.format(self.path, fileName)
        # 初始化文件写入 文件名 编码解码器 帧率 文件大小
        # VWirte = cv2.VideoWriter('123asd.avi', cv2.VideoWriter_fourcc('I', '4', '2', '0'), fps,
        VWirte = cv2.VideoWriter(filePath, cv2.VideoWriter_fourcc('X', 'V', 'I', 'D'), self.videoFps, size)
        success, frame = camera.read()  # 只写10帧
        numFramesRemaining = self.recordTime * self.videoFps  # z
        while success and numFramesRemaining:
            VWirte.write(frame)
            success, frame = camera.read()
            numFramesRemaining -= 1
        time.sleep(1)  # y延迟一秒关闭摄像头 否则会出现 terminating async callback 异步处理错误
        camera.release()  # 释放摄像头
        VWirte.release()  # 释放文件
        if self.isUpdate:
            t = threading.Thread(target=self.updateQiniu,args=(filePath,fileName,))
            t.start()
            # self.updateQiniu(filePath,fileName)
        self.isRecording = False
        return True

    def updateQiniu(self, localfile,fileName):
        # 构建鉴权对象
        q = Auth(self.access_key, self.secret_key)       
        # 生成上传 Token，可以指定过期时间等
        token = q.upload_token(self.bucket_name, fileName, 3600)
        print('正在上传：{}'.format(fileName))
        ret, info = put_file(token, fileName, localfile)
        if os.path.exists(localfile) and self.isDelete:
            try:
                os.remove(localfile)
            except IOError:
                print('系统错误，无法删除文件-' + fileName + '，可能被占用')
        return True



if __name__ == '__main__':
    rv = recordVideoClass()
    rv.run()
